package com.spsoft.security.interceptor;

import cn.hutool.extra.spring.SpringUtil;

import com.spsoft.core.annotation.AnonymousAccess;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.LoginException;

import com.spsoft.core.utils.StringUtil;
import com.spsoft.security.interceptor.handler.AuthorityHandlerProcess;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查
 * 1.配置到拦截器要拦截哪些请求
 * 2.把这些配置放在容器中
 *
 * 实现HandlerInterceptor接口
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 目标方法执行之前
     * 登录检查写在这里，如果没有登录，就不执行目标方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//      获取进过拦截器的路径
//        String requestURI = request.getRequestURI();
        // 登录检查逻辑

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AnonymousAccess authority = handlerMethod.getMethod().getAnnotation(AnonymousAccess.class);
           String authorization = request.getHeader("Authorization");
            if(StringUtil.isNotBlank(authorization)){
                AuthorityHandlerProcess authorityHandlerProcess = SpringUtil.getBean(AuthorityHandlerProcess.class);
                authorityHandlerProcess.process(authorization,request,authority);
               return  true;
            }
            throw new LoginException(ResponseEnum.LOGIN_ERROR);
        }
           return true;
    }

    /**
     * 目标方法执行完成以后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 页面渲染以后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
